package q828_uniqueLetterString;

public class Solution_3 {
    /*
    实际上逻辑和solution1是一致的
     */
    public int uniqueLetterString(String s) {
        int n = s.length();
        if (n == 1) {
            return 1;
        }
        char[] ch = s.toCharArray();
        int[] left = new int[n];
        int[] right = new int[n];
        for (int i = 0; i < n; i++) {
            left[i] = -1;
            right[i] = n;
        }

        int[] prev = new int[26];
        int[] next = new int[26];
        for (int i = 0; i < 26; i++) {
            prev[i] = -1;
            next[i] = n;
        }

        for (int i = 0; i < n; i++) {
            int idx = ch[i] - 'A';
            left[i] = prev[idx];
            prev[idx] = i;
        }

        for (int i = n - 1; i >= 0; i--) {
            int idx = ch[i] - 'A';
            right[i] = next[idx];
            next[idx] = i;
        }

        int res = 0;
        for (int i = 0; i < n; i++) {
            res += (i - left[i]) * (right[i] - i);
        }

        return res;
    }
}
